<?php
/**
 * Created by PhpStorm.
 * User: 何培春
 * Date: 2017/8/11
 * Time: 23:20
 */

namespace Admin\Controller;
use Think\Controller;

class TopicController extends BaseControlle
{
    public function __construct()
    {
        parent::__construct();
    }

    //p标签过滤
    private function MyReplace($str){
        $search = array('<p>','</p>','\n','\t');
        $replace = array("","","","");
        return trim(str_replace($search,$replace,$str));
    }
    //添加题目
    public function NewTopic(){
        if(IS_POST){
            $sequence  = I("post.sequence");
            $body      = I('post.body','',false);
            $title      = I('post.title');
            $body      = htmlspecialchars($this->MyReplace(xss_clean($body)));
            $option    = I('post.option',array(),false);
            $answer    = I('post.answer');
            $type      = I("post.type",1,'intval');
            $examinationid = I('post.examinationid');
            $LastJobLibraryId = I('post.LastJobLibraryId',0,'intval');
            $status = I('post.status');
            $add_date = date(time());
            //初始化选择题的选项
            $options = array();
            if($type == 1 || $type == 2){
                $result = array();
                $result_num = count(array_filter($answer));
                if ($result_num == 0){
                    $this->ajaxReturn(array('code'=>500,'msg'=>'请选择正确答案'));
                }
                $type    = ($result_num==1)?1:2;

                foreach ($answer as $k=>$v){
                    $result[$v] = $v;
                }
                //防止跨站攻击
                foreach ($option as $item=>$value) {
                    $options[$item] = htmlspecialchars($this->MyReplace(xss_clean($value)));
                }
            }elseif ($type == 3 || $type == 4 || $type == 5 || $type == 6){
                $result = htmlspecialchars($this->MyReplace(xss_clean($answer)));
            }

            $db = array(
                'sequence'=>$sequence,
                'title'=>$title,
                'body'=>$body,
                'type'=>$type,
                'options'=>serialize($options),
                'result'=>serialize($result),
                'examinationid'=>$examinationid,
                'add_date'=>$add_date,
                'add_uid'=>1,
                'last_job_library_id'=>$LastJobLibraryId,
                'status'=>$status
            );

            $job_library = M('job_library');
            $ret = $job_library->data($db)->add();

            if($ret){
                $this->ajaxReturn(array('code'=>200));
            }else{
                $this->ajaxReturn(array('code'=>501,'msg'=>'数据添加失败！'));
            }
        }else{
            $this->ajaxReturn(array('code'=>502,'msg'=>'提交非法数据！'));
        }
    }

    public function UpImage()
    {
        $config = array(
            'maxSize'  => 3145728,
            'rootPath' => './Uploads',
            'savePath' => '/images/',
            'saveName' => array('uniqid'),
            'exts'      => array('jpg', 'gif', 'png', 'jpeg'),
            'autoSub'  => true,
            'subName'  => array('date','Ymd'),);
        $upload = new \Think\Upload($config);// 实例化上传类
        $info = $upload->upload();

        if (!$info) {
            // 上传错误提示错误信息
            $this->error($upload->getError());
        } else {
            // 上传成功
            $this->ajaxReturn(array('code'=>0,'msg'=>'上传成功','data'=>array('src'=>'Uploads'.$info['file']['savepath'].$info['file']['savename'])));
        }
    }
    public function CKeditUpImage()
    {
        $CKEditorFuncNum = I("get.CKEditorFuncNum");
        $config = array(
            'maxSize'  => 3145728,
            'rootPath' => './Uploads',
            'savePath' => '/images/',
            'saveName' => array('uniqid'),
            'exts'      => array('jpg', 'gif', 'png', 'jpeg'),
            'autoSub'  => true,
            'subName'  => array('date','Ymd'),);
        $upload = new \Think\Upload($config);// 实例化上传类
        $info = $upload->upload();
        //compressed_image(APP_ROOT.'./Uploads'.$info['upload']['savepath'].$info['upload']['savename']);

        if (!$info) {
            // 上传错误提示错误信息
            $this->error($upload->getError());
        } else {
            // 上传成功
            echo '<script>window.parent.CKEDITOR.tools.callFunction('.$CKEditorFuncNum.', \'Uploads'.$info['upload']['savepath'].$info['upload']['savename'].'\', \'\');</script>';
            //$this->ajaxReturn(array('code'=>0,'msg'=>'上传成功','data'=>array('src'=>'Uploads'.$info['file']['savepath'].$info['file']['savename'])));
        }
        exit();
    }

    //添加题目UI
    public function NewTopicUI(){
        $examinationid = I('get.examinationid',0,'intval');
        if ($examinationid == 0){
            $this->error('请选择正确的题库');
        }
        $job_library = M('job_library');
        $ret_job_library = $job_library->where(array('examinationid'=>$examinationid,'type'=>5))->select();
        $this->assign('ret_job_library',$ret_job_library);
        $this->assign('examinationid',$examinationid);
        $this->display();
    }

    //更新题目UI
    public function EditTopic(){
        $TopicId = I('get.topicid');
        $job_library = M('job_library');
        $ret_job_library = $job_library->where("id='$TopicId'")->find();
        $ret_job_library['body'] = htmlspecialchars_decode($ret_job_library['body']);

        $job_library = M('job_library');
        $last_job_library_id = $job_library->where(array('examinationid'=>$ret_job_library['examinationid'],'type'=>5))->select();
        $this->assign('last_job_library_id',$last_job_library_id);
        $this->assign('library',$ret_job_library);
        $this->assign('option',unserialize($ret_job_library['options']));
        $this->assign('answer',unserialize($ret_job_library['result']));
        $this->display();
    }

    //更新题目
    public function UpdataTopic(){
        if(IS_POST){
            $sequence = I("post.sequence");
            $title      = I('post.title');
            $body     = I('post.body','',false);
            $body      = htmlspecialchars($this->MyReplace(xss_clean($body)));
            $option  = I('post.option','',false);
            $answer   = I('post.answer');
            $LastJobLibraryId = I('post.LastJobLibraryId',0,'intval');
            $type     = I("post.type");
            $id = I('post.id');
            $status = I('post.status');
            $update_date = date(time());

            //初始化选择题的选项
            $options = array();
            if($type == 1 || $type == 2){
                $result = array();
                $result_num = count(array_filter($answer));
                if ($result_num == 0){
                    $this->ajaxReturn(array('code'=>500,'msg'=>'请选择正确答案'));
                }
                $type    = ($result_num==1)?1:2;
                foreach ($answer as $k=>$v){
                    $result[$v] = $v;
                }
                //防止跨站攻击
                foreach ($option as $item=>$value) {
                    $options[$item] = htmlspecialchars($this->MyReplace(xss_clean($value)));                }
            }elseif ($type == 3 || $type == 4 || $type == 5 || $type == 6){
                $result = htmlspecialchars($this->MyReplace($answer));
            }

            $db = array(
                'sequence'=>$sequence,
                'body'=>$body,
                'title'=>$title,
                'type'=>$type,
                'options'=>serialize($options),
                'result'=>serialize($result),
                'update_date'=>$update_date,
                'update_uid'=>1,
                'last_job_library_id'=>$LastJobLibraryId,
                'status'=>$status
            );

            $job_library = M('job_library');
            $ret = $job_library->where("id='$id'")->save($db);

            if($ret){
                $this->ajaxReturn(array('code'=>200));
            }else{
                $this->ajaxReturn(array('code'=>501,'msg'=>'数据修改失败！'));
            }
        }else{
            $this->ajaxReturn(array('code'=>502,'msg'=>'提交非法数据！'));
        }
    }

    //删除题目
    public function DeleteTopic(){
        $TopicId = I('post.topicid');
        $TopicId = intval($TopicId);

        $job_library = M('job_library');
        $exam_topic  = M('exam_topic');
        $ret_job_library = $job_library->where("id='$TopicId'")->delete();
        $ret_exam_topic  = $exam_topic->where("job_library_id='$TopicId'")->delete();

        if($ret_job_library && $ret_exam_topic){
            $this->ajaxReturn(array('code'=>200));
        }elseif ($ret_job_library || $ret_exam_topic){
            $this->ajaxReturn(array('code'=>200,'msg'=>'删除出了点小问题，但是成功了！'));
        }else{
            $this->ajaxReturn(array('code'=>500,'msg'=>'删除失败！'));
        }
    }

    //管理题目
    public function Manage(){
        $examinationid = I('get.examinationid');
        $page = I('get.page');
        $job_library    = M('job_library');
        $count          = $job_library->where("examinationid='$examinationid' AND status!=3")->count();

        $page = DBPage($count,30,$page);

        $library = $job_library->where("examinationid='$examinationid' AND status!=3")->limit(30)->page($page['page'])->order('sequence asc,id asc')->select();
        $this->assign('library',$library);
        $this->assign('examinationid',$examinationid);
        $this->assign('count',$page['countPage']);
        $this->assign('page',$page['page']);
        $this->display();
    }
}